﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Mengsk.ERP.Orders;
using Mengsk.ERP.Orders.TDOrderInterfaces;
using Mengsk.ERP.Processors;
using Mengsk.ERP.Database;
using Microsoft.Win32;
using System.Diagnostics;

namespace Mengsk.ERP.App.AddressCheck
{
    /// <summary>
    /// AddressCheckUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class AddressCheckUserControl : UserControl, IUIPlugin
    {
        private List<OrderViewModel> orders = new List<OrderViewModel>();
        private bool isLoaded = false;

        public AddressCheckUserControl()
        {
            InitializeComponent();
        }

        public string Title
        {
            get { return "地址处理"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (isLoaded == false)
            {
                Broadcast.MessageCenter.Instance.MessageArrived += new EventHandler<Broadcast.MessageArrviedEventArgs>(Instance_MessageArrived);
                Broadcast.MessageCenter.Instance.Start();
            }
            isLoaded = true;
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            Broadcast.MessageCenter.Instance.MessageArrived -= new EventHandler<Broadcast.MessageArrviedEventArgs>(Instance_MessageArrived);
            //不要调用Stop
            //Broadcast.MessageCenter.Instance.Stop();
        }

        void Instance_MessageArrived(object sender, Broadcast.MessageArrviedEventArgs e)
        {
            if (e.Message == null)
            {
                return;
            }

            if (e.Message.GetType() != typeof(OrderChangedMessage))
            {
                return;
            }

            OrderChangedMessage m = e.Message as OrderChangedMessage;
            this.Dispatcher.BeginInvoke(new Action(() => this.UpdateOrderFromMessage(m)));
        }

        private OrderViewModel GetCurrentModel()
        {
            if (this.dgvOrders.SelectedCells.Count < 1)
            {
                return null;
            }

            return this.dgvOrders.SelectedCells[0].Item as OrderViewModel;
        }

        private void UpdateOrderFromMessage(OrderChangedMessage message)
        {
            OrderViewModel order = this.orders.FirstOrDefault(obj => obj.Order.Shop == message.Shop && obj.Order.POPID == message.OrderID);
            if (order == null)
            {
                return;
            }

            order.Order.Flag = message.Flag;
            order.Order.SellerComment = message.SellerComment;
            order.SellerComment = message.SellerComment;
            order.Flag = OrderImageUtil.Convert(message.Flag);
            order.Order.Address = message.Address;
        }

        private void UpdateOrder(OrderViewModel order, OrderFlag flag, string comment, bool appendAlready = true)
        {
            try
            {
                if (order == null)
                {
                    return;
                }
                comment += string.Format("【{0} {1}】", App.UserName, DateTime.Now.ToString("MM-dd HH:mm"));
                if (appendAlready && string.IsNullOrWhiteSpace(order.SellerComment) == false)
                {
                    comment = order.SellerComment + " " + comment;
                }
                TDOrderInterfaceBase orderInterface = TDOrderInterfaceBase.GetOrderInterfaceSource(order.Order.Shop);
                orderInterface.UpdateOrderComment(order.Order.POPID, flag, comment);
                order.Order.SellerComment = comment;
                order.Order.Flag = flag;
                order.SellerComment = comment;
                order.Flag = OrderImageUtil.Convert(flag);
                Broadcast.MessageCenter.Instance.SendMessage(new OrderChangedMessage { Address = order.Order.Address, Flag = flag, SellerComment = comment, OrderID = order.Order.POPID, Sender = "", Shop = order.Order.Shop, Targets = new string[0], Time = DateTime.Now });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "更新失败");
            }
        }

        private void UpdateSelectedOrder(OrderFlag flag, string comment, bool appendAlreay = true)
        {
            try
            {
                this.UpdateOrder(this.GetCurrentModel(), flag, comment, appendAlreay);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "更新失败");
            }
        }

        private void miYTArrive_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.GREEN, "到", true);
        }

        private void miZhaiArrive_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.BLUE, "宅到", true);
        }


        private void miYTArriveAndReturn_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.GREEN, "到回头客", true);
        }

        private void miZhaiArriveAndReturn_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.BLUE, "宅到回头客", true);
        }


        private void startManualEdit_Click(object sender, RoutedEventArgs e)
        {
            var order = this.GetCurrentModel();
            if (order == null)
            {
                return;
            }
            OrderEdit or = new OrderEdit { Flag = order.Order.Flag, Comment = order.Order.SellerComment };
            if (or.ShowDialog().Value)
            {
                this.UpdateOrder(order, or.Flag, or.Comment, false);
            }
        }

        private void miYTArrvieTown_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.YELLOW, "圆到镇", true);
        }

        private void miZhaiArriveTown_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.YELLOW, "宅到镇");
        }

        private void miYTArrvieCountry_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.YELLOW, "圆到县");
        }

        private void miZhaiArriveCountry_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.YELLOW, "宅到县");
        }

        private void miAddressNotClear_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.YELLOW, "地址不明");
        }

        private void noneArrvie_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateSelectedOrder(OrderFlag.RED, "不到");
        }

        private void noneArrvieAndClose_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.UpdateSelectedOrder(OrderFlag.RED, "不到");
                var order = this.GetCurrentModel();
                var tdInterface = TDOrderInterfaceBase.GetOrderInterfaceSource(order.Order.Shop);
                tdInterface.CloseOrder(order.Order.POPID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Handles the Click event of the btnRefresh control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //从网络中下载订单
                DownloadingWindow window = new DownloadingWindow { OrderManagers = TDOrderInterfaceBase.AllOrderInterfaces };
                bool? ret = window.ShowDialog();

                if (ret == null || ret != true)
                {
                    return;
                }

                var orders = window.Orders.Where(obj => obj.Flag == OrderFlag.UN_LABEL || (obj.Flag == OrderFlag.RED && obj.SellerComment.Contains("不到") == false)).Select(
                    obj => new OrderViewModel { Order = obj, Flag = OrderImageUtil.Convert(obj.Flag), SellerComment = obj.SellerComment }).ToArray();
                if (orders.Length < 1)
                {
                    this.dgvOrders.ItemsSource = null;
                    this.orders.Clear();
                    MessageBox.Show("没有找到需要检查地址的订单");
                    return;
                }

                //分析
                for (int i = 0; i < orders.Length; i++)
                {
                    
                    //读取本地历史订单
                    var localHistoryOrders1 = ERP.Orders.OrderManager.Instance.GetOrdersByNameAndPopIDNotEqual(orders[i].Order.Name, orders[i].Order.POPID);
                    var localHistoryOrders2 = ERP.Orders.OrderManager.Instance.GetOrdersByPhoneOrMobileAndPopIDNotEqual(orders[i].Order.PhoneMobile == "" ? orders[i].Order.Phone : orders[i].Order.PhoneMobile, orders[i].Order.POPID);
                    var localHistoryOrders3 = ERP.Orders.OrderManager.Instance.GetOrdersByRealNameAndAddressAndPopIDNotEqual(orders[i].Order.RealName, orders[i].Order.Address, orders[i].Order.POPID);

                    List<Order> allLocalHistoryOrders = new List<Order>();
                    foreach (var order in localHistoryOrders1)
                    {
                        if (allLocalHistoryOrders.Contains(order) == false && orders.FirstOrDefault(obj => obj.Order.POPID == order.POPID) == null)
                        {
                            allLocalHistoryOrders.Add(order);
                        }
                    }

                    foreach (var order in localHistoryOrders2)
                    {
                        if (allLocalHistoryOrders.Contains(order) == false && orders.FirstOrDefault(obj => obj.Order.POPID == order.POPID) == null)
                        {
                            allLocalHistoryOrders.Add(order);
                        }
                    }

                    foreach (var order in localHistoryOrders3)
                    {
                        if (allLocalHistoryOrders.Contains(order) == false && orders.FirstOrDefault(obj => obj.Order.POPID == order.POPID) == null)
                        {
                            allLocalHistoryOrders.Add(order);
                        }
                    }


                    //从网络更新历史订单
                    foreach (var historyOrder in allLocalHistoryOrders)
                    {
                        var tmpOrder = TDOrderInterfaceBase.GetOrderInterfaceSource(historyOrder.Shop).DownLoadOrder(historyOrder.POPID, historyOrder.CreateTime, false);
                        if (tmpOrder == null)
                        {
                            tmpOrder = TDOrderInterfaceBase.GetOrderInterfaceSource(historyOrder.Shop).DownLoadOrder(historyOrder.POPID, historyOrder.CreateTime, false);
                        }
                        if (tmpOrder == null)
                        {
                            tmpOrder = TDOrderInterfaceBase.GetOrderInterfaceSource(historyOrder.Shop).DownLoadOrder(historyOrder.POPID, historyOrder.CreateTime, false);
                        }
                        if (tmpOrder == null)
                        {
                            MessageBox.Show(string.Format("订单编号:{0},用户:{1}", historyOrder.POPID, historyOrder.Name), "下载历史订单最新信息,已经重试3次失败");
                            continue;
                        }

                        historyOrder.State = tmpOrder.State;
                        historyOrder.Flag = tmpOrder.Flag;
                        historyOrder.SellerComment = tmpOrder.SellerComment;
                    }

                    orders[i].HistoryOrder = allLocalHistoryOrders.Select(obj => new OrderViewModel { Order = obj, Flag = OrderImageUtil.Convert(obj.Flag), SellerComment = obj.SellerComment }).ToArray();

                    //检查地址中是否含村
                    if (orders[i].Order.Address.Contains('村'))
                    {
                        orders[i].Background = Brushes.LightBlue;
                    }

                    //检查是否有重复
                    foreach (var or in orders)
                    {
                        if (orders[i].Order.Equals(or.Order))
                        {
                            continue;
                        }
                        if (orders[i].Order.Name.Equals(or.Order.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            orders[i].Background = or.Background = Brushes.Yellow;
                        }
                        if (orders[i].Order.PhoneMobile == or.Order.PhoneMobile && string.IsNullOrWhiteSpace(or.Order.PhoneMobile) == false)
                        {
                            orders[i].Background = or.Background = Brushes.Yellow;
                        }
                        if (orders[i].Order.Phone == or.Order.Phone && string.IsNullOrWhiteSpace(or.Order.Phone) == false)
                        {
                            orders[i].Background = or.Background = Brushes.Yellow;
                        }
                        if (orders[i].Order.RealName == or.Order.RealName && orders[i].Order.Address == or.Order.Address)
                        {
                            orders[i].Background = or.Background = Brushes.Yellow;
                        }
                    }

                    //检查是否有拒收
                    foreach (var order in allLocalHistoryOrders)
                    {
                        if (order.State == "STATE_COD_REFUSE")
                        {
                            orders[i].Background = Brushes.Red;
                            break;
                        }
                    }

                    ////检查手机地址
                    //try
                    //{
                    //    if (string.IsNullOrWhiteSpace(orders[i].Order.PhoneMobile) == false)
                    //    {
                    //        var phoneRet = Phone.PhoneUtil.GetPhoneAddress(orders[i].Order.PhoneMobile);
                    //        if (orders[i].Order.Address.Contains(phoneRet.Province) == false && orders[i].Order.Address.Contains(phoneRet.City) == false)
                    //        {
                    //            orders[i].Background = Brushes.Red;
                    //        }
                    //        orders[i].PhoneAddress = phoneRet.Province + " " + phoneRet.City + " " + phoneRet.Corp;
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    MessageBox.Show(ex.Message, "读取手机归属地失败");
                    //}


                }
                this.orders.Clear();
                this.orders.AddRange(orders);
                this.dgvOrders.ItemsSource = orders;
                this.tbTotal.Text = "当前共 : " + orders.Length + " 条记录";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private void dgvOrders_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (this.dgvOrders.SelectedCells.Count < 1)
                {
                    this.dgvHistoryItem.ItemsSource = null;
                    return;
                }

                this.dgvHistoryItem.ItemsSource = (this.dgvOrders.SelectedCells[0].Item as OrderViewModel).HistoryOrder;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                this.dgvHistoryItem.ItemsSource = null;
            }
        }

        private void historyClose_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var orderViewModel = this.dgvHistoryItem.SelectedCells[0].Item as OrderViewModel;
                this.UpdateOrder(orderViewModel, OrderFlag.RED, "");
                var tdInterface = TDOrderInterfaceBase.GetOrderInterfaceSource(orderViewModel.Order.Shop);
                tdInterface.CloseOrder(orderViewModel.Order.POPID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void historyCloseStartManualEdit_Click(object sender, RoutedEventArgs e)
        {
            if (this.dgvHistoryItem.SelectedCells.Count < 1)
            {
                return;
            }
            var order = this.dgvHistoryItem.SelectedCells[0].Item as OrderViewModel;
            if (order == null)
            {
                return;
            }
            OrderEdit or = new OrderEdit { Flag = order.Order.Flag, Comment = order.Order.SellerComment };
            if (or.ShowDialog().Value)
            {
                this.UpdateOrder(order, or.Flag, or.Comment);
            }
        }

        private void startPPCRM_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.ClassesRoot, Microsoft.Win32.RegistryView.Default);
                RegistryKey hTen = key.OpenSubKey("Tencent");

                if (hTen == null)
                {
                    throw new Exception("没有找到注册信息 HKEY_CLASSES_ROOT\\Tencent");
                }

                string programPath = hTen.GetValue("URL Protocol", "").ToString();

                if (string.IsNullOrWhiteSpace(programPath))
                {
                    throw new Exception("注册表中的QQ启动程序为空");
                }

                OrderViewModel vm = this.GetCurrentModel();
                if (vm == null)
                {
                    MessageBox.Show("没有选择用户");
                    return;
                }
                string cmdargs = string.Format("\"{0}\" \"tencent://message/?uin={1}&Site=拍拍网&Menu=yes\"", programPath, vm.Order.Name);
                Process.Start("\"" + programPath + "\"", string.Format("\"tencent://message/?uin={0}&Site=拍拍网&Menu=yes\"", vm.Order.Name));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
